var express = require('express');
const { parseInt } = require('lodash');
const _=require("lodash");
var router = express.Router();

//模拟数据库数据
let stus=[
  {id:202201,name:"tom",age:18},
  {id:202202,name:"rose",age:16},
  {id:202203,name:"jack",age:20},
  {id:202204,name:"lili",age:15},
  {id:202205,name:"lucy",age:15}
];

/* GET home page. */
router.get('/', function(req, res, next) {
  res.render('student', {stus,msg:"",stu:{id:"",name:"",age:""}});
});

router.get('/delete/:id', function(req, res, next) {
  //在stus中查找编号为id的元素索引
  let index=_.findIndex(stus,{id:req.params.id});
  //删除索引为index的元素
  stus.splice(index,1);
  res.render('student', {stus,msg:"删除成功！",stu:{id:"",name:"",age:""}});
});


router.get('/edit/:id', function(req, res, next) {
  //在stus中查找编号为id的元素
  let stu=_.find(stus,{id:parseInt(req.params.id)});
  res.render('student', {stus,stu,msg:""});
});

//添加
router.post('/add', function(req, res, next) {
  let stu=req.body;

  //根据编号排序
  let stus2=_.orderBy(stus,["id"]);
  stu.id=_.last(stus2).id+1;  //取最后一个元素的编号加1

  stus.push(stu);

  res.render('student', {stus,msg:"添加成功！",stu:{id:"",name:"",age:""}});
});



//更新
router.post('/update', function(req, res, next) {
  //获取提交的数据对象
  let stuSubmit=req.body;
  //在集合中查找要更新的元素
  let stu=_.find(stus,{id:parseInt(stuSubmit.id)}); 
  //更新名字与年龄
  stu.name=stuSubmit.name;
  stu.age=stuSubmit.age;
  //重新渲染页面，指定学生列表数据，学生数据，与提示消息
  res.render('student', {stus,msg:"更新成功！",stu:{id:"",name:"",age:""}});
});

module.exports = router;
